﻿using AutoMapper;
using D.B.Data.API.Applications.Command.MenusCommand;
using D.B.Data.Domain;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;

namespace D.B.Data.API.Applications.CommandHandler.MenusCommandHandler
{
    public class AddMenusCommandHandler : IRequestHandler<AddMenusCommand, APIResult<int>>
    {
        private readonly IBaseRepository<MenusModel> baseRepository;
        private readonly IMapper mapper;

        public AddMenusCommandHandler(IBaseRepository<MenusModel> baseRepository, IMapper mapper)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
        }

        public Task<APIResult<int>> Handle(AddMenusCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();

            //查询选择父级 里所有的子集
            var list = baseRepository.GetAll().Where(s => s.Pid == request.Pid&&!s.IsDel).Select(s=>s.MenuName);

           var Isname=list.Contains(request.MenuName);
            if(Isname)
            {
                result.Code=EnumCode.File;
                result.Msg = "菜单名称重复";
                return Task.FromResult(result);
            }

            var data=mapper.Map<MenusModel>(request);
            data.Rank = 0;
            data.CreateTime= DateTime.Now;
            data.CreateUserId = request.UserId;

            var count=baseRepository.Add(data);
            if(count>0)
            {
                result.Code = EnumCode.Ok;
                result.Msg = "添加成功";
            }
            else
            {
                result.Code = EnumCode.File;
                result.Msg = "添加失败";
            }
         
            return Task.FromResult(result);



        }
    }
}
